/*
 * @Description: 函数作用说明
 * @Author: zdq
 * @Date: 2024-12-18 21:53:30
 * @LastEditTime: 2024-12-26 20:13:50
 * @LastEditors: zdq
 * @Reference:
 */
import { ref } from 'vue'
import { TableDataGoodInfoOrderCreate } from './types'

const goods = ref<Array<TableDataGoodInfoOrderCreate>>([
  // {
  //   code: '',
  //   goodsName: '',
  //   goodsSpecName: '',
  //   goodsBrand: '',
  //   qty: 0,
  //   img: '',
  //   buyTime: '',
  //   name: '',
  //   phone: '',
  //   province: '',
  //   city: '',
  //   area: '',
  //   town: '',
  //   address: '',
  //   isEmptyLine: true,
  //   type: 0,
  //   goodId: '',
  //   goodSpecId: '',
  //   codeId: '',
  //   goodsSpecCode: '',
  //   warrantyDay: undefined,
  // },
])

export default () => {
  const addGood = (good: TableDataGoodInfoOrderCreate) => {
    const goodIds = goods.value.map((item) => item.goodId)
    const goodSpecIds = goods.value.map((item) => item.goodSpecId)
    const codes = goods.value.map((item) => item.code)
    if (
      !goodIds.includes(good.goodId) ||
      !goodSpecIds.includes(good.goodSpecId) ||
      !codes.includes(good.code)
    ) {
      goods.value.push(good)
    }
  }

  const removeGood = (goodId: string, goodSpecId: string, code: string) => {
    const goodIndex = goods.value.findIndex(
      (item) => item.goodId === goodId && item.goodSpecId === goodSpecId && item.code === code,
    )
    if (goodIndex >= 0) {
      goods.value.splice(goodIndex, 1)
    }
  }

  const clearAllGoods = () => {
    goods.value = goods.value.filter((good) => good.type !== 3)
  }

  const clearAllRegisterCodes = () => {
    goods.value = goods.value.filter((good) => good.type !== 1)
  }

  const clearAllNoRegisterCodes = () => {
    goods.value = goods.value.filter((good) => good.type !== 2)
  }

  const findGood = (goodId: string, goodSpecId: string, code: string) => {
    return goods.value.find(
      (good) => good.goodId === goodId && good.goodSpecId === goodSpecId && good.code === code,
    )
  }

  return {
    goods,
    addGood,
    findGood,
    removeGood,
    clearAllGoods,
    clearAllRegisterCodes,
    clearAllNoRegisterCodes,
  }
}
